<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Address;
use App\Models\AddressSnapshot;
use App\Models\Balance;
use App\Models\Order;
use App\Models\Product;
use App\Models\ProductSnapshot;
use App\Services\BalanceService;
use Illuminate\Http\Request;

class OrderController extends BaseController
{
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $input = $request->input();
        $search = ['user_id' => $this->getUserId()];
        $list = Order::with('product_snapshot')->apply($search, $input)->orderBy("id", "desc")
            ->paginate(per_page());
        return $this->paginate($list);
    }

    /**
     * 下单
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function store(Request $request) {
        $this->validate($request, [
            'product_id' => 'required',
            'area' => 'required',
            'detail' => 'required',
            'contact' => 'required',
            'phone' => 'required',
        ]);
        $product_id = \request("product_id");
        $input = $request->input();

        return \DB::transaction(function () use($input, $product_id) {
            $product = Product::lockForUpdate()->find($product_id);
            if (!$product)
                return $this->failed('商品不存在');

            if ($product->stock <= 0)
                return $this->failed('商品已被兑完，待官方补货');

            $product->stock -= 1;
            $product->sell_num += 1;
            $product->save();

            $user = $this->getUser();
            if ($user->balance < $product->money)
                return $this->failed('粮票余额不够');

            $address = Address::where('user_id', $user->id)->where('contact', $input['contact'])->where('phone', $input['phone'])
                ->where('area', $input['area'])->where('detail', $input['detail'])->first();
            if (!$address) {
                $address = Address::create([
                    'user_id' => $user->id,
                    'contact' => $input['contact'],
                    'phone' => $input['phone'],
                    'area' => $input['area'],
                    'detail' => $input['detail']
                ]);
            }

            $arr = $product->toArray();
            $product_snapshot = new ProductSnapshot();
            foreach ($arr as $key => $value) {
                if ($key == 'id') {
                    $product_snapshot->product_id = $value;
                } else {
                    $product_snapshot-> {$key} = $value;
                }
            }
            $product_snapshot->save();

            $order_sn = create_order_no('m');
            $user_id = $this->getUserId();
            $order = Order::create([
                'user_id' => $user_id,
                'order_sn' =>  $order_sn,
                'product_id' => $product->id,
                'product_snapshots_id' => $product_snapshot->id,
                'num' => 1,
                'address_snapshots_id' => $address->id,
                'status' => Order::STATUS_WAIT_DELIVER,
                'money' => $product->money
            ]);

            BalanceService::store($user_id, -$product->money, Balance::TYPE_BUY_PRODUCT, false);

            return $this->success(['order_sn' => $order_sn, 'id' => $order->id]);
        });


    }

}

